package com.example.demo.Util;

import com.example.demo.Entity.ShopUser;
import org.springframework.stereotype.Component;
import org.springframework.web.cors.CorsUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        //用Session提取userId来验证登陆
        HttpSession session = request.getSession();
        //userId，登陆时放入session的
        String userId = (String) session.getAttribute("uid");
        if (request != null && CorsUtils.isPreFlightRequest(request)) {
            return true;
        }
        //未登陆
        if (userId == null) {
            //在返回头部设置标志
            response.addHeader("FLAG", "-1");
            response.setHeader("SESSIONSTATUS", "TIMEOUT");
            //重定向目标地址
            response.setHeader("CONTEXTPATH", "/");
            //这个方法返回false表示忽略当前请求
            return false;
        } else {
            //放行，用户即可继续调用自己需要的接口
            return true;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
        // TODO Auto-generated method stub
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        // TODO Auto-generated method stub
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
